<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";
import { getLineData } from "../../api/statistics";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "550px",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      chartData: {
        dates: [],
        values: [],
      },
    };
  },

  mounted() {
    this.$nextTick(async () => {
      this.initChart();
      let res = await getLineData();
      let raw = res.data;
      this.chartData = {
        dates: raw.map((i) => i.date),
        values: raw.map((i) => i.count),
      };
      this.setOptions(this.chartData);
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, "macarons");
      this.setOptions(this.chartData);
    },
    setOptions({ dates = [], values = [] } = {}) {
      this.chart.setOption({
        xAxis: {
          data: dates,
          boundaryGap: false,
          axisTick: {
            show: false,
          },
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
          padding: [5, 10],
        },
        yAxis: {
          axisTick: {
            show: false,
          },
        },
        legend: {
          data: ["患者新增数"],
        },
        series: [
          {
            name: "患者新增数",
            type: "line",
            smooth: true,
            data: values,
            itemStyle: {
              normal: {
                color: "#3888fa",
                lineStyle: {
                  color: "#3888fa",
                  width: 2,
                },
                areaStyle: {
                  color: "#f3f8ff",
                },
              },
            },
            animationDuration: 1200,
            animationEasing: "quadraticOut",
          },
        ],
      });
    },
  },
};
</script>
